import { defineStore } from 'pinia';
import { message as $message } from 'ant-design-vue';
import { useWsStore } from './ws';
import type { RouteRecordRaw } from 'vue-router';
import { store } from '@/store';
import { handleGetToken, handleLogin } from '@/api/login';
import { ACCESS_TOKEN_KEY } from '@/enums/cacheEnum';
import { Storage } from '@/utils/Storage';
import { logout, permmenu } from '@/api/account';
import { generatorDynamicRouter } from '@/router/generator-router';
import { resetRouter } from '@/router';

interface UserState {
  token: string;
  name: string;
  username:string;
  avatar: string;
  // like [ 'sys:user:add', 'sys:user:update' ]
  perms: string[];
  menus: RouteRecordRaw[];
  userInfo: Partial<API.AdminUserInfo>;
  mixMenuParent: string;
}

export const useUserStore = defineStore({
  id: 'user',
  state: (): UserState => ({
    token: Storage.get(ACCESS_TOKEN_KEY, null),
    name: '',
    username:'',
    avatar: '',
    perms: [],
    menus: [],
    userInfo: {},
    mixMenuParent: '',
  }),
  getters: {
    getToken(): string {
      return this.token;
    },
    getAvatar(): string {
      return this.avatar;
    },
    getName(): string {
      return this.name;
    },
    getPerms(): string[] {
      return this.perms;
    },
    getUserAccount():string {
      return this.username;
    }
  },
  actions: {
    //设置Mix模式下的一级菜单
    setMixMenuParent(mixMenuParent: '') {
      console.log(mixMenuParent, 'mixMenuParent');
      this.mixMenuParent = mixMenuParent;
    },
    /** 清空token及用户信息 */
    resetToken() {
      this.avatar = this.token = this.name = '';
      this.perms = [];
      this.menus = [];
      this.userInfo = {};
      Storage.clear();
    },
    /** 登录成功保存token */
    setToken(token: string) {
      this.token = token ?? '';
      const ex = 7 * 24 * 60 * 60 * 1000;
      Storage.set(ACCESS_TOKEN_KEY, this.token, ex);
    },
    /** 登录 */
    async login(params) {
      try {
        this.resetToken();
        const data: any = await handleGetToken(params);
        if (data && data.error == 200) {
          this.setToken(data.result.token);
        } else {
          $message.error('用户名或密码错误');
          return Promise.reject();
        }
        const res: any = await handleLogin(params);
        if (res && res.error == 200) {
          this.name = res.result.name;
          this.username= res.result.username;
          this.userInfo = res.result;
        } else {
          $message.error('用户名或密码错误');
          return Promise.reject();
        }
        return this.afterLogin();
      } catch (error) {
        return Promise.reject(error);
      }
    },
    /** 登录成功之后, 获取用户信息以及生成权限路由 */
    async afterLogin() {
      try {
        const res = await permmenu({perms:'S'});
        if (res && res.error == 200) {
          const getFullPath = (route, routeMap) => {
            if (route.parentId == '0') {
              return `/${route.path}`;
            } else {
              const parent = routeMap.find((item) => item.menuId == route.parentId);
              return `${getFullPath(parent, routeMap)}/${route.path}`;
            }
          };
          const menus = res.result.map((item, index) => {
            return {
              id: item.menuId,
              name: item.title,
              parentId: item.parentId == '0' ? null : item.parentId,
              viewPath: item.component,
              icon: item.iconSvg,
              isShow: item.show == 1,
              keepAlive: item.keepAlive || false,
              router: getFullPath(item, res.result),
              type: item.component ? 1 : 0,
              isExt: item.isFrame == '1',
              openMode: 2,
              orderNum: index,
            };
          });
          const generatorResult = await generatorDynamicRouter(menus);
          this.menus = generatorResult.menus.filter((item) => !item.meta?.hideInMenu);
          return this.menus;
        } else {
          return Promise.reject();
        }
      } catch (error) {
        return Promise.reject(error);
        // return this.logout();
      }
    },
    /** 登出 */
    async logout() {
      // await logout();
      const wsStore = useWsStore();
      wsStore.closeSocket();
      this.resetToken();
      resetRouter();
    },
  },
});

// 在组件setup函数外使用
export function useUserStoreWithOut() {
  return useUserStore(store);
}
